
import { history, connect, useDispatch, useModel } from 'umi';
import { Row, Col, Form, Button, Space, Upload,message } from 'antd';
import React,{ useEffect, useState } from 'react';
import { useLocation } from 'react-router'
import {
  FormTime,
  FormSelect,
  FormInput,
} from '@/components/SearchForm/SearchFormItem';
import { uploadFileUrl } from '@/service/common/upload';
import styles from './index.less';
import cardStyles from '../index.less';
import { orderDeliveryCar } from '@/service/order';
import { formatDate } from '@/utils/common/dateFilter';
import {  getCookie } from '@/utils/cookie';
import {getUseList} from '@/service/system/user'

const formLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 12, offset: 0 },
  },
};
function Delivery(props: any) {
  const dispatch = useDispatch();
  const {
    global: { currentRoute },
  } = props;
  // 获取路由中订单编号
  const location = useLocation()
  const [orderIds,setOrderIds] = useState('')
  const routerName = () => {
      setOrderIds(location?.search?.split('id=')[1])
  }
  useEffect(()=>{
      routerName()
  },[orderIds])
  const { initialState } = useModel('@@initialState');
  const [loading, setLoading] = useState(false) // 按钮状态
  const { fileName } = initialState || {};
  // cookies中获取公司id
  const merchantIds: any = getCookie('orgId');
  const [workerList,setWorkerList] = useState<any>([]); // 工作人员列表
  useEffect(()=>{
    getUseList({merchantId:merchantIds}).then((res)=>{
      if(res?.success){
        setWorkerList(res.data)
      }
        
    })
  },[merchantIds])
  const onCancel = () => {
    dispatch({
      type: 'global/deleteTabs',
      payload: currentRoute,
    });
    history.goBack();
  };
  const onFinish = (values: any) => {
    setLoading(true)
    const value1 = {...values}
    value1.deliveryTime = formatDate(value1.deliveryTime, 'YYYY-MM-DD HH:mm:ss');
    workerList?.forEach((res:any)=>{
      if(res.id === value1?.deliveryPersonId){
        value1.deliveryPerson = res.name
      }
    })
    orderDeliveryCar(orderIds, value1).then((res:any)=>{
      if (res.success) {
        onCancel();
        setTimeout(() => setLoading(false), 1000)
      }else{
        setTimeout(() => setLoading(false), 1000)
      }
    });
  };

  const onFinishFailed = (errorInfo: any) => errorInfo;
  const [fileList, setFileList] = useState<any>([]);
  const [form] = Form.useForm();
  
 
  //  文件上传生成上传信息
const uploadProps = {
  action: uploadFileUrl,
  name: fileName, // 滴滴上传:file 测试上传:files
  data: {
    modelName: 'carOrder',
    targetAttr: 2,
  },
  beforeUpload: (file: any) => {
    const isLt200M = file.size / 1024 / 1024 < 200
    if (!isLt200M) {
      message.error('文件必须小于200MB')
    }
    return isLt200M
  },
  onChange(info: any) {
    if (info.file.status === 'done') {
      setFileList(info?.fileList);
      const list:any = []
      info?.fileList?.map((res:any)=>list.push(res?.response?.data?.id?.toString()))
      form.setFieldsValue({attachmentList:list});
    }
    setFileList(info?.fileList);
  },
  onRemove(info: any) {
    form.setFieldValue('attachmentList','');
    message.success(`${info?.name}移除成功`)
  },
  fileList,
};
  return (
    <div className={cardStyles.card} id="deliveryCarInfo">
      <p className={cardStyles.title}>交车信息</p>
      <div className={styles.form}>
        <Form
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          {...formLayout}
          form={form}
        >
          <Row gutter={24} className={cardStyles.rows}>
            <Col span={24}>
              <FormTime
                label="交车时间"
                name="deliveryTime"
                subtype="date"
                placeholder="请选择交车时间"
                rules={[{ required: true, message: '请选择交车时间' }]}
                style={{ width: '300px' }}
              />
            </Col>
            <Col span={24}>
              <FormSelect
                name="deliveryPersonId"
                label="交车工作人员"
                items={workerList}
                placeholder="交车工作人员"
                keys='id'
                title='name'
                rules={[{ required: true, message: '请选择交车工作人员' }]}
                style={{ width: '300px' }}
              />
            </Col>
            <Col span={24}>
              <FormInput
                name="remark"
                label="备注"
                maxLength={200}
                placeholder="请填写绑车备注信息，不超过200个字符"
                allowClear
                style={{ width: '600px' }}
              />
            </Col>
            <Col span={24}>
              <Form.Item
                label="交车附件"
                name="attachmentList"
                rules={[{ required: true, message: '请上传交车附件' }]}
              >
                <Upload {...uploadProps}>
                    {fileList?.length >= 5 ? null : <Button>请选择文件</Button>}
                </Upload>
                <p style={{ margin: '15px 0 0 0' }}>
                  清单说明：附件最大支持200M，
                </p>
                <p>支持格式：PDF、Word、Excel、JPG、PNG</p>
              </Form.Item>
            </Col>
          </Row>
          <Row justify="center" className={cardStyles.rows}>
            <Form.Item>
              <Space>
                <Button shape="round" onClick={onCancel}>
                  取消
                </Button>
                <Button shape="round" type="primary" htmlType="submit" loading={loading}>
                  提交
                </Button>
              </Space>
            </Form.Item>
          </Row>
        </Form>
      </div>
    </div>
  );
}

export default connect(({ order: { details }, global }: any) => ({
  orderId: details.id,
  global,
}))(Delivery);
